
import axios from 'axios'

export default {
  state () {
    return {
      list: []
    }
  },
  mutations: {
    changeList (state, list) {
      state.list = list
    }
  },
  actions: {
    async getList ({ commit }) {
      const res = await axios('http://localhost:3000/cart')
      console.log(res)
      commit('changeList', res.data)
    },
    syncCount ({ commit }, obj) {
      return new Promise(async (resolve, reject) => {
        const res = await axios.patch('http://localhost:3000/cart/' + obj.id,
          {
            count: obj.count
          })
        console.log(res)
        resolve(res)
      })
    }
  },
  getters: {
    total (state) { return state.list.reduce((sum, item) => sum + item.count, 0) },
    totalPrice (state) { return state.list.reduce((sum, item) => sum + item.count * item.price, 0) },
  },
  namespaced: true
}